<template>
  <div class="app-container">
    <el-form :model="form" :inline="true" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            prop="customerName"
            label="公&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp司:"
          >
            <el-select
              style="width: 90%"
              v-model="form.customerName"
              filterable
              placeholder="请选择公司名称"
              @change="handleCaseNameChange"
              clearable
            >
              <el-option
                v-for="item in companyData"
                :key="item.customerName"
                :label="item.customerName"
                :value="item.customerName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="&nbsp&nbsp案&nbsp件&nbsp日&nbsp期:"
            prop="offerDate"
          >
            <el-date-picker
              readonly
              v-model="form.offerDate"
              type="date"
              placeholder="请选择案件日期"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="&nbsp&nbsp客戶簡稱:" prop="abbreviation">
            <el-input
              v-model="form.abbreviation"
              placeholder="请输入客户简称"
              readonly
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="預計出貨日:" prop="caseDate">
            <el-date-picker
              v-model="form.caseDate"
              type="date"
              placeholder="请选择預計出貨日"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="&nbsp&nbsp聯繫人:"
            prop="clientName"
            style="font-weight: bold"
          >
            <!-- <el-input v-model="form.caseName" placeholder="请输入项目" /> -->
            <el-select
              style="width: 85%; margin-left: 15px"
              v-model="form.clientName"
              filterable
              placeholder="请选择客戶聯繫人"
              clearable
            >
              <el-option
                v-for="item in caseOptions"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="&nbsp&nbsp當&nbsp前&nbsp進&nbsp度:"
            prop="schedule"
          >
            <el-input
              v-model="form.schedule"
              placeholder="请输入案件當前進度"
              disabled
              style="width: 220px"
            />
          </el-form-item>
        </el-col>
      </el-row>
 
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="項目名稱:" prop="caseName">
            <el-input v-model="form.caseName" placeholder="请输入項目名稱" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="addQuotation"
            label="&nbsp&nbsp总&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp价:"
            prop="caseValue"
          >
            <el-input
              v-model="form.caseValue"
              readonly
              placeholder="总价"
              style="width: 220px"
            />
          </el-form-item>

     
          <el-form-item
            v-if="!addQuotation"
            label="&nbsp&nbsp新建报价单:"
            prop="caseValue"
          >
            <el-link
              :href="getQuotationLink()"
              target="_blank"
              type="primary"
              :underline="true"
              style="font-size: 14px"
            >
              <el-icon style="margin-right: 4px"><Plus /></el-icon>
              新增报价单
            </el-link>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
  <el-col :span="12">
    <el-form-item v-if="addQuotation" label="&nbsp&nbsp案&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp值:" prop="caseValue">
      <el-input v-model="form.totalSelectedPrice" readonly placeholder="案值" style="width: 200px" />
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item v-if="addQuotation" label="&nbsp&nbsp运&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp费:" prop="freight">
      <el-input v-model="form.freight" readonly placeholder="运费" style="width: 220px" />
    </el-form-item>
  </el-col>
 </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="&nbsp&nbsp負責業務:" prop="nickName">
         
            <el-select v-model="form.nickName" style="width: 200px" placeholder="请选择负责业务">
              <el-option
                v-for="item in businessOptions"  
                :key="item.nickName"
                :label="item.nickName"
                :value="item.nickName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-steps
            style="max-width: 1000px"
            :space="100"
            :active="activeStep"
            v-if="addQuotation"
            finish-status="success"
          >
            <el-step title="設計階段" />
            <el-step title="報價提供" />
            <el-step title="修改待確認" />
            <el-step title="報價單待回簽" />
            <el-step title="系統訂單" />
            <el-step title="出貨" />
            <el-step title="追加" />
            <el-step title="結案" />
          </el-steps>
        </el-col>
      </el-row>
    </el-form>
    <br />
    <br />
    <br />
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          v-hasPermi="['system:case:add']"
          @click="submitForm()"
          >提交</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Plus"
          v-if="addQuotation"
          v-hasPermi="['system:case:add']"
          @click="addRow()"
          >進度維護</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:case:export']"
          v-if="addQuotation"
          >案件導出</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="View"
          @click="handleViewQuotation"
          v-hasPermi="['system:case:add']"
          v-if="addQuotation"
          >瀏覽及修改報價單</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button v-if="addQuotation" v-hasPermi="['system:case:add']">
          <el-link
            :href="addgetQuotationLink()"
            target="_blank"
            type="success"
            :underline="true"
            style="font-size: 14px"
          >
            <el-icon style="margin-right: 4px"><Plus /></el-icon>
            新增/追加報價單
          </el-link>
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain icon="Close" @click="handleClose"
          >关闭</el-button
        >
      </el-col>
    </el-row>
    <br />

    <!-- 可编辑表格V2 -->
    <div class="tb-container" ref="tbContainerRef">
      <h2 style="margin: 0; text-align: center">進度維護</h2>

      <!-- 表格 -->
      <el-table
        :data="testDatas"
        border
        style="width: 100%; margin-top: 10px"
        @cell-dblclick="cellDblclick"
        @header-contextmenu="
          (column, $event) => rightClick(null, column, $event)
        "
        @row-contextmenu="rightClick"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          v-for="(col, idx) in columnList"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :index="idx"
        >
          <template #default="scope">
            <template v-if="col.prop === 'scheduleInfo'">
              <el-input
                type="textarea"
                v-model="scope.row[col.prop]"
                placeholder="请输入進度說明"
                clearable
              />
            </template>
            <template v-else-if="col.prop === 'quotation'">
              <router-link
                :to="'/offer/case/select/' + form.id"
                class="link-type"
              >
                <span>報價明細</span>
              </router-link>
            </template>
            <template v-else-if="col.prop === 'scheme'">
              <file-upload v-model="scope.row.url" />
            </template>
            <el-select
              v-if="col.prop === 'scheduleState'"
              v-model="scope.row[col.prop]"
              placeholder="请选择"
              clearable
              @change="updateFormSchedule"
            >
              <el-option
                v-for="option in availableStatusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
         
          </template>
        </el-table-column>
      </el-table>
      <!-- <p style="text-align: left; color: #ccc">右键菜单，双击编辑</p> -->

      <!-- <div>
      <h3 style="text-align: center">实时数据展示</h3>
      <label>当前目标：</label>
      <p>{{ JSON.stringify(curTarget) }}</p>
      <label>表头：</label>
      <p v-for="col in columnList" :key="col.prop">{{ JSON.stringify(col) }}</p>
      <label>数据：</label>
      <p v-for="(data, idx) in testDatas" :key="idx">{{ JSON.stringify(data) }}</p>
    </div> -->

      <!-- 右键菜单框 -->
      <!-- <div v-show="showMenu" id="contextmenu" @mouseleave="showMenu = false"> -->
        <!-- <i class="el-icon-circle-close hideContextMenu" @click="showMenu = false"></i>
      <el-button size="mini" type="primary" @click="addColumn()">前方插入一列</el-button>
      <el-button size="mini" type="primary" @click="addColumn(true)">后方插入一列</el-button>
      <el-popconfirm title="确定删除该列吗？" @confirm="delColumn">
        <template #reference>
          <el-button type="primary" size="mini">删除当前列</el-button>
        </template>
      </el-popconfirm> -->
        <!-- <el-button size="mini" type="primary" @click="renameCol($event)">更改列名</el-button> -->
        <!-- <div v-show="!curTarget.isHead">
          <hr />
          <el-button size="mini" type="primary" @click="addRow()"
            >上方插入一行</el-button
          > -->
          <!-- <el-button size="mini" type="primary" @click="addRow(true)">下方插入一行</el-button> -->
          <!-- <el-popconfirm title="确定删除该行吗？" @confirm="delRow">
            <template #reference>
              <el-button type="primary" size="mini">删除当前行</el-button>
            </template>
          </el-popconfirm>
        </div>
      </div> -->

      <!-- 单元格/表头内容编辑框 -->
      <!-- <div
        v-show="showEditInput"
        id="editInput"
        @mouseleave="showEditInput = false"
      >
        <el-input
          placeholder="请输入内容"
          v-model="curTarget.val"
          clearable
          @change="updTbCellOrHeader"
        >
          <template #prepend>{{ curColumn.label || curColumn.prop }}</template>
        </el-input>
      </div> -->
    </div>
  </div>
</template>
   
   <script setup name="case">
import {
  listcase,
  addcase,
  getcasebybusinessId,
  updatecase,
  selectUser,
} from "@/api/business/case.js";

import {
  listbusinesscustomerName,
  getbusinessAndcase,
} from "@/api/business/add.js";

import { ref, reactive, computed, watch } from "vue";
import { getUserProfile } from "@/api/system/user";

const router = useRouter();
const { proxy } = getCurrentInstance();
const businessOptions = ref([]);
// 解构数据
// 定义数据
const columnList = computed(() => {
  const baseColumns = [
    { prop: "scheduleTime", label: "日期" },
    { prop: "scheduleInfo", label: "進度說明" },
    { prop: "scheduleState", label: "案件進度狀態" },
    { prop: "scheme", label: "方案" },
  ];

  // 如果 addQuotation 为 true，则添加报价单列
  // if (addQuotation.value) {
  //   baseColumns.splice(3, 0, { prop: "quotation", label: "報價單" });
  // }

  return baseColumns;
});
const testDatas = ref([
  {
    scheduleTime: new Date(),
    scheduleInfo: "",
    scheduleState: "",
    quotation: "",
    scheme: "",
  },
]);

// 定义一个函数来格式化日期
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

// 在需要的地方调用 formatDate 函数
testDatas.value.forEach((item) => {
  item.scheduleTime = formatDate(item.scheduleTime);
});
const showMenu = ref(false);
const showEditInput = ref(false);
const curTarget = reactive({
  rowIdx: null,
  colIdx: null,
  val: null,
  isHead: undefined,
});
const countCol = ref(0);

const availableStatusOptions = ref([]);
const allStatusOptions = [
  { value: "開案圖紙設計階段", label: "開案圖紙設計階段" },
  { value: "方案及報價提供", label: "方案及報價提供" },
  { value: "方案報價修改待確認", label: "方案報價修改待確認" },
  { value: "報價單待回簽", label: "報價單待回簽" },
  { value: "系統訂單", label: "系統訂單" },
  { value: "出貨", label: "出貨" },
  { value: "追加", label: "追加" },
  { value: "結案", label: "結案" },
];

// 计算属性
const curColumn = computed(() => columnList.value[curTarget.colIdx] ?? {});

//查询及修改报价单
function handleViewQuotation() {
  router.push(`/offer/case/select/${form.value.id}`);
}
function cellDblclick(row, column, cell, $event) {
  showEditInput.value = false;
  if (column.index == null) return;

  // 检查当前列的属性是否为 'scheduleTime'
  if (
    column.property === "scheduleTime" ||
    column.property === "scheme" ||
    column.property === "quotation"
  ) {
    return;
  }

  locateMenuOrEditInput("editInput", 200, $event);
  showEditInput.value = true;

  Object.assign(curTarget, {
    rowIdx: row.row_index,
    colIdx: column.index,
    val: row[column.property],
    isHead: false,
  });
}

function rightClick(row, column, $event) {
  $event.preventDefault();
  showMenu.value = false;
  if (column.index == null) return;
  locateMenuOrEditInput("contextmenu", 140, $event);
  showMenu.value = true;
  Object.assign(curTarget, {
    rowIdx: row ? row.row_index : null,
    colIdx: column.index,
    val: row ? row[column.property] : column.label,
    isHead: !row,
  });
}
//查询业务员并赋值给下拉选
function getUserList() {
  selectUser().then((response) => {

    businessOptions.value = response.data;
  
  });
}

function renameCol($event) {
  showEditInput.value = false;
  if (curTarget.colIdx === null) return;
  locateMenuOrEditInput("editInput", 200, $event);
  showEditInput.value = true;
}

// 返回按钮
function handleClose() {
  const obj = { path: "/business/case/add" };
  proxy.$tab.closeOpenPage(obj);
}

function updTbCellOrHeader(val) {
  if (!curTarget.isHead)
    testDatas.value[curTarget.rowIdx][curColumn.value.prop] = val;
  else {
    if (!val) return;
    columnList.value[curTarget.colIdx].label = val;
  }
}

function addRow(later) {
  showMenu.value = false;
  const idx = later ? curTarget.rowIdx + 1 : curTarget.rowIdx;
  let obj = {};
  columnList.value.forEach((p) => (obj[p.prop] = ""));
  obj.scheduleTime = new Date().toISOString().split("T")[0]; // 设置当前系统日期
  testDatas.value.splice(idx, 0, obj);
}

function delRow() {
  showMenu.value = false;
  if (curTarget.rowIdx !== null) {
  
    // 删除指定行
    testDatas.value = testDatas.value.filter(
      (_, index) => index !== curTarget.rowIdx
    );

 
  }
}

function addColumn(later) {
  showMenu.value = false;
  const idx = later ? curTarget.colIdx + 1 : curTarget.colIdx;
  const colStr = { prop: "col_" + ++countCol.value, label: "" };
  columnList.value.splice(idx, 0, colStr);
  testDatas.value.forEach((p) => (p[colStr.prop] = ""));
}

function delColumn() {
  showMenu.value = false;
  testDatas.value.forEach((p) => {
    delete p[curColumn.value.prop];
  });
  columnList.value.splice(curTarget.colIdx, 1);
}

function tableRowClassName({ row, rowIndex }) {
  row.row_index = rowIndex;
}

const tbContainerRef = ref();

function locateMenuOrEditInput(eleId, eleWidth, $event) {
  // 表格容器的位置
  const { x: tbX, y: tbY } = tbContainerRef.value.getBoundingClientRect();
  // 当前鼠标位置
  const { x: pX, y: pY } = $event;
  const ele = document.getElementById(eleId);
  ele.style.top = pY - tbY - 6 + "px";
  ele.style.left = pX - tbX - 6 + "px";
  if (window.innerWidth - eleWidth < pX - tbX) {
    ele.style.left = "unset";
    ele.style.right = 0;
  }
}

// 初始化格式化的选项数据
const formattedOptions = ref([]);
const caseList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const addQuotation = ref(false);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const loadAll = ref([]);
const route = useRoute();
const close = ref(false);
const companyData = ref([]);
const caseOptions = ref([]);
const activeStep = ref(0);
const username = ref("");
const userphone = ref("");

const data = reactive({
  form: {
    businessId: "",
    nickName: '',
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    businessId: route.params.Id,
  },
  rules: {
    customerName: [
      { required: true, message: "客户名称不能为空", trigger: "blur" },
    ],

    caseName: [
      { required: true, message: "项目名称不能为空", trigger: "blur" },
    ],
    caseDate: [{ required: true, message: "日期不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 查询列表
async function getList() {
  loading.value = true;

  try {
    // 获取业务和案例数据
    const businessResponse = await getbusinessAndcase();
    // 处理公司数据
 handleBusinessResponse(businessResponse);

    // 如果有业务ID，获取具体案例数据
    if (queryParams.value.businessId) {
      const caseResponse = await getcasebybusinessId(
        queryParams.value.businessId,
        dateRange.value
      );


   

      
 
      
      handleCaseResponse(caseResponse);
    }
  } catch (error) {
    console.error("Failed to fetch data:", error);
  } finally {
    loading.value = false;
  }
}

// 处理业务数据响应
function handleBusinessResponse(response) {


  companyData.value = response.rows.map((item) => ({

    
    
    customerName: item.customerName,
    abbreviation: item.abbreviation,

    contactsVos: item.contactsVos,
    businessId: item.id,
  }));


  caseList.value = response.rows;
 

  // 更新进度状态
  if (testDatas.value.length > 0) {
    form.value.schedule = testDatas.value[0].scheduleState;
    setActiveStep(testDatas.value[0].scheduleState);
  }
}

// 处理案例数据响应
function handleCaseResponse(response) {


 
  close.value = true;
  addQuotation.value = true;
  const responseData = response.data;


  
  
  // 处理客户名称
  if (responseData.name) {
    responseData.clientName = responseData.name;
    delete responseData.name;
  }
 




  // 计算总价值
  responseData.caseValue =
    (Number(responseData.freight) || 0) +
    (Number(responseData.totalSelectedPrice) || 0);


  form.value = responseData;


  



  // 更新进度数据
  if (responseData.scheduleCaseVos?.length > 0) {
    const firstElement = testDatas.value[0];
    // 格式化后端返回的日期
    const formattedScheduleCaseVos = responseData.scheduleCaseVos.map(
      (item) => ({
        ...item,
        scheduleTime: formatDate(new Date(item.scheduleTime)),
      })
    );
    testDatas.value = [firstElement, ...formattedScheduleCaseVos];
  }

  handleCaseNameChange(form.value.customerName);
}

// 处理公司名称变化
function handleCaseNameChange(value) {
  // 找到对应的 companyData 项

  const selectedCompany = companyData.value.find(
    (item) => item.customerName === value
  );
  if (selectedCompany) {
    form.value.abbreviation = selectedCompany.abbreviation;
    // form.value.nickName = selectedCompany.nickName;
    form.value.businessId = selectedCompany.businessId;
    // 更新 caseOptions 为 selectedCompany 的 contactsVos
    caseOptions.value = selectedCompany.contactsVos.map((contact) => ({
      name: contact.name,
      contacetId: contact.id,
    }));
  } else {
    form.value.abbreviation = "";
    caseOptions.value = [];
  }
}

//生成报价单
function getQuotationLink(quotation) {
  const encodedUsername = encodeURIComponent(username.value);
  const encodedPhone = encodeURIComponent(userphone.value);
  return `http://192.168.110.11:8087/?username=${encodedUsername}&phone=${encodedPhone}`;
}

//追加或者新增报价单
function addgetQuotationLink(quotation) {
  const encodedUsername = encodeURIComponent(username.value);
  const encodedPhone = encodeURIComponent(userphone.value);
  return `http://192.168.110.11:8087/?username=${encodedUsername}&phone=${encodedPhone}&caseId=${form.value.id}`;
}

// /** 查询公司列表  应该是全查现在是分页*/
// function getListbusiness() {
//   loading.value = true;
//   listbusinesscustomerName(queryParams.value.businessId,dateRange.value).then(response => {
//     const customerNames = response.rows.map(item => ({
//       value: item.customerName,
//       businessId: item.id,
//       link: item.customerName // 可以根据实际情况添加链接
//     }));
//     loadAll.value = customerNames;
//     loading.value = false;
//   }).catch(error => {
//     console.error('Failed to fetch company list:', error);
//     loading.value = false;

//   })
// };

// 获取当前的年月日时分
const getCurrentDateTime = () => {
  return new Date();
};

/** 導出按钮操作 */
function handleExport() {
  proxy.download(
    "case/exportSchedule",
    {
      ...queryParams.value,
    },
    `项目明细_${new Date().getTime()}.xlsx`
  );
}

function reset() {
  form.value = {};
  proxy.resetForm("addclientele");
}
/** 添加角色 */
function handleAdd() {
  reset();

  open.value = true;
  title.value = "添加案件";
  getListbusiness();
}

/** 提交按钮 */
function submitForm() {
  //如果预计出货日为空不允许提交
  if (form.value.caseDate == "" || form.value.caseDate == null || form.value.caseDate == undefined) {
    proxy.$modal.msgError("預計出貨日不能为空");
    return; // 阻止提交
  }
  // 过滤掉所有 scheduleState 为空的数据，包括第一行
  const scheduleCase = testDatas.value.filter((item) => {
    // 只保留有 scheduleState 的数据
    return item.scheduleState && item.scheduleState.trim() !== "";
  });
  if (scheduleCase.length === 0) {
    proxy.$modal.msgError("案件进度状态不能为空");
    return; // 阻止提交
  }

  // 合并数据
  const mergedData = { ...form.value, scheduleCase };
  if (form.value.id != undefined) {
    updatecase(mergedData).then((response) => {
      proxy.$modal.msgSuccess("修改成功");
      handleClose();
    });
  } else {
    addcase(mergedData).then((response) => {
      proxy.$modal.msgSuccess("新增成功");
      handleClose();
      // getList();
    });
  }
}

//获取用户名
function getUser() {
  getUserProfile().then((response) => {

    username.value = response.data.nickName; // 直接赋值
    userphone.value = response.data.phonenumber;
  });
}

// 更新表单进度
function updateFormSchedule(value) {
  if (
    testDatas.value.length > 0 &&
    testDatas.value[0].scheduleState === value
  ) {
    form.value.schedule = value;
    setActiveStep(value);
  }
}

// 设置 activeStep
function setActiveStep(scheduleState) {
  switch (scheduleState) {
    case "開案圖紙設計階段":
      activeStep.value = 1;
      break;
    case "方案及報價提供":
      activeStep.value = 2;
      break;
    case "方案報價修改待確認":
      activeStep.value = 3;
      break;
    case "報價單待回簽":
      activeStep.value = 4;
      break;

    case "系統訂單":
      activeStep.value = 5;
      break;
    case "出貨":
      activeStep.value = 6;
      break;
    case "追加":
      activeStep.value = 7;
      break;
    case "結案":
      activeStep.value = 8;
      break;

    default:
      activeStep.value = 1;
  }
}

watch(
  testDatas,
  (newVal) => {
   
    const currentStates = newVal
      .filter((item) => item.scheduleState) // 过滤掉空状态
      .map((item) => item.scheduleState);

  

    if (currentStates.length === 0) {
      availableStatusOptions.value = allStatusOptions.filter(
        (option) => option.value === "開案圖紙設計階段"
      );
    } else if (currentStates.includes("結案")) {
      availableStatusOptions.value = allStatusOptions.filter(
        (option) => option.value === "開案圖紙設計階段"
      );
    } else if (currentStates.includes("追加")) {
      availableStatusOptions.value = allStatusOptions.filter(
        (option) => option.value === "結案" || option.value === "出貨"
      );
    } else if (currentStates.includes("出貨")) {
      availableStatusOptions.value = allStatusOptions.filter(
        (option) => option.value === "結案" || option.value === "追加"
      );
    } else if (currentStates.includes("系統訂單")) {
      availableStatusOptions.value = allStatusOptions.filter(
        (option) => option.value === "出貨"
      );
    } else if (currentStates.includes("報價單待回簽")) {
      availableStatusOptions.value = allStatusOptions.filter(
        (option) => option.value === "系統訂單"
      );
    } else if (currentStates.includes("方案報價修改待確認")) {
      availableStatusOptions.value = allStatusOptions.filter(
        (option) =>
          option.value === "報價單待回簽" || option.value === "方案及報價提供"
      );
    } else if (currentStates.includes("方案及報價提供")) {
      availableStatusOptions.value = allStatusOptions.filter(
        (option) =>
          option.value === "方案報價修改待確認" ||
          option.value === "報價單待回簽"
      );
    } else if (currentStates.includes("開案圖紙設計階段")) {
      availableStatusOptions.value = allStatusOptions.filter(
        (option) => option.value === "方案及報價提供"
      );
    }
    // 如果 newVal 的长度大于 1，更新 form 的 schedule 属性并设置 active step
    if (newVal.length > 1) {
      form.value.schedule = newVal[1].scheduleState;
      setActiveStep(newVal[1].scheduleState);
    }
  },
  { immediate: true, deep: true }
);

// 在组件挂载时执行
onMounted(() => {
  form.value.offerDate = getCurrentDateTime();
  getList();
  getUser();
  getUserList();
});
</script>
  
  <style lang="scss" scoped>
.linkman-input-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.linkman-input-group .el-input {
  flex: 1;
  margin-right: 10px;
}

.form-item {
  margin-bottom: 20px; /* 确保每个表单项有相同的底部间距 */
}
.tb-container {
  position: relative;
}
#contextmenu {
  position: absolute;
  top: 0;
  left: 0;
  height: auto;
  width: 120px;
  border-radius: 3px;
  border: 1px solid #999999;
  background-color: #f4f4f4;
  padding: 10px;
  z-index: 12;
  button {
    display: block;
    margin: 0 0 5px;
    width: 100%;
    font-size: 12%;
  }
}
.hideContextMenu {
  position: absolute;
  top: 5px;
  right: 5px;
}
#editInput,
#headereditInput {
  position: absolute;
  top: 0;
  left: 0;
  height: auto;
  min-width: 200px;
  max-width: 400px;
  padding: 0;
  z-index: 12;
}
#editInput .el-input,
#headereditInput .el-input {
  outline: 0;
  border: 1px solid #c0f2f9;
  border-radius: 5px;
  box-shadow: 0px 0px 10px 0px #c0f2f9;
}
</style>